//
//  SISSAddressPickerView.m
//  SISSAPP
//
//  Created by 袁应荣 on 2019/8/8.
//  Copyright © 2019 优房网. All rights reserved.
//

#import "SISSAddressPickerView.h"

#define PickerHeight 246
#define PickerToolBarHeight 44

@interface SISSAddressPickerView ()<UIPickerViewDelegate,UIPickerViewDataSource>

//picker控件数据源
@property(nonatomic,strong)NSMutableArray *showAddressArr;
//picker控件默认展示的元素下标
@property(nonatomic,strong)NSMutableArray *showIndexs;

@property (nonatomic, strong) UIView *pickerContainerView;

@property (nonatomic,strong) UIWindow *alertWindow;

@property (nonatomic,strong) UIView *backgroundView;

@property (nonatomic, strong) UIPickerView *pickerView;
@property (weak, nonatomic) UILabel *titleLabel;

@property (nonatomic,strong) UITapGestureRecognizer *tap;

@end
@implementation SISSAddressPickerView


- (instancetype)initWithFrame:(CGRect)frame {
    self =  [super initWithFrame:frame];
    if (self) {
        [self initUI];
        
        
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initUI];
    }
    return self;
}

-(void)setTitle:(NSString *)title {
    _title = title;
    self.titleLabel.text = title;
}


- (void)initUI {
    
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
    
    _alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _alertWindow.windowLevel = UIWindowLevelAlert;
    self.frame = _alertWindow.bounds;
    
    //添加 底部遮罩
    _backgroundView = [[UIView alloc]initWithFrame:_alertWindow.bounds];
    
    _backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
    [self addSubview:_backgroundView];
    [self setUserInteractionEnabled:YES];
    [self setMultipleTouchEnabled:NO];
    [self.backgroundView setUserInteractionEnabled:YES];
    [self.backgroundView setMultipleTouchEnabled:NO];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    self.tap = tap;
    [_backgroundView addGestureRecognizer:tap];
    
    
    self.pickerContainerView = [UIView new];
    self.pickerContainerView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, (PickerHeight + PickerToolBarHeight) * 2 + (PickerHeight + PickerToolBarHeight));
    self.pickerContainerView.backgroundColor = UIColor.whiteColor;
    
    
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, PickerToolBarHeight)];
    toolBar.barTintColor = [UIColor whiteColor];
    
    UIBarButtonItem *noSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    noSpace.width = 10;
    
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonClickAction:)];;
    doneBtn.tintColor = [UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1.0];
    
    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonClickAction:)];
    cancelBtn.tintColor = [UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1.0];
    
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBar setItems:[NSArray arrayWithObjects:noSpace,cancelBtn,flexSpace,doneBtn,noSpace, nil]];
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(0, 0, 200, PickerToolBarHeight);
    titleLabel.center = toolBar.center;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = self.title ? self.title : @"省市区选择";
    [toolBar addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, PickerToolBarHeight, [UIScreen mainScreen].bounds.size.width, PickerHeight)];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.pickerView.backgroundColor = [UIColor whiteColor];
    
    [self.pickerContainerView addSubview:toolBar];
    [self.pickerContainerView addSubview:self.pickerView];
    [self addSubview:self.pickerContainerView];
    
    [self showWithAnimation:YES];
}

#pragma mark-- UIPickerViewDataSource
//列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return [self.showIndexs count];
}

//每列个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [[self.showAddressArr objectAtIndex:component] count];
}


#pragma mark-- UIPickerViewDelegate
//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
//    UILabel *label = (id)view;
//    if (!label) {
//        label= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
//        label.textAlignment = NSTextAlignmentCenter;
//        label.textColor = [UIColor blackColor];
//        NSDictionary *dic = [[self.showAddressArr objectAtIndex:component] objectAtIndex:row];
//        label.text = dic[@"text"];
//    }
//    return label;
//}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSDictionary *dic = [[self.showAddressArr objectAtIndex:component] objectAtIndex:row];
    
    return dic[@"text"];
}

//点击选择
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSArray *columnItems = [self.showAddressArr objectAtIndex:component];
    NSDictionary *selectedItem = [columnItems objectAtIndex:row];
    
    if ([selectedItem[@"childrens"] count] == 0) {
        //此时为最后一列可能就一列或多列的最后一列
        [self.showIndexs replaceObjectAtIndex:component withObject:@(row)];
    } else {
        
        NSUInteger replaceIdx = component;
        BOOL next = true;
        while (next) {
            if (component == replaceIdx) {
                [self.showIndexs replaceObjectAtIndex:replaceIdx withObject:@(row)];
            }else{
                
                if (replaceIdx < [self.showIndexs count]) {
                    
                    [self.showAddressArr replaceObjectAtIndex:replaceIdx withObject:selectedItem[@"childrens"]];
                    [self.showIndexs replaceObjectAtIndex:replaceIdx withObject:@(0)];
                    selectedItem = [selectedItem[@"childrens"] firstObject];
                }else{
                    next = false;
                }
            }
            
            replaceIdx ++;
        }
        
    }
    [pickerView reloadAllComponents];
    //实时更新选择数据及联数据
    for (NSInteger index = 0; index < [self.showIndexs count]; index ++) {
        
        [self.pickerView selectRow:[[self.showIndexs objectAtIndex:index] integerValue] inComponent:index animated:NO];
    }
}

- (instancetype)initWithDefaultValues:(NSArray *)defaultValues {
    return [self initWithTitle:@"广东省市区选择" defaultValues:defaultValues];
}

- (instancetype)initWithTitle:(NSString *)title defaultValues:(NSArray *)defaultValues {
    
    if (self = [super init]) {
//        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.title = title;
        self.showIndexs = [NSMutableArray array];
        self.showAddressArr = [NSMutableArray array];
        //加载本地json数据
//        NSString *provinceJsonPath = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
//        NSData *provinceData = [[NSData alloc] initWithContentsOfFile:provinceJsonPath];
//        NSError *error = nil;
//        NSArray *provinceArr = [NSJSONSerialization JSONObjectWithData:provinceData options:kNilOptions error:&error];
        
        NSString *cityJsonPath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
        NSData *cityData = [[NSData alloc] initWithContentsOfFile:cityJsonPath];
        NSError *error = nil;
        NSDictionary *cityDict = [NSJSONSerialization JSONObjectWithData:cityData options:kNilOptions error:&error];
        NSString *districtJsonPath = [[NSBundle mainBundle] pathForResource:@"district" ofType:@"json"];
        NSData *districtData = [[NSData alloc] initWithContentsOfFile:districtJsonPath];
//        NSError *error = nil;
        NSDictionary *districtDict = [NSJSONSerialization JSONObjectWithData:districtData options:kNilOptions error:&error];
        NSMutableArray *citysArr = [NSMutableArray arrayWithArray:cityDict[@"440000"]];
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:citysArr.count];
        for (NSDictionary *dict in citysArr) {
            NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithDictionary:dict];
            [dictM setObject:districtDict[dict[@"value"]] forKey:@"childrens"];
            [arrM addObject:dictM];
        }
        //初始化源数据
        [self defaultShowValue:[NSMutableArray arrayWithArray:defaultValues] items:arrM];
        
    }
    return self;
}


- (void)defaultShowValue:(NSMutableArray *)values items:(NSArray *)items {
    [items enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if ([@"" isEqualToString:[values firstObject]]) {
//            //values中没有默认值的时候values中的元素目前为@""空字符
//            [self.showIndexs addObject:@(0)];
//            [values removeObjectAtIndex:0];
//            [self.showAddressArr addObject:items];
//            [self defaultShowValue:values items:obj[@"childrens"]];
//
//        } else
            if ([obj[@"text"] isEqualToString:[values firstObject]])  {
            [self.showIndexs addObject:@(idx)];
            [values removeObjectAtIndex:0];
            [self.showAddressArr addObject:items];
            [self defaultShowValue:values items:obj[@"childrens"]];
        }
    }];
    if (self.showIndexs.count == 0) {
        [self defaultShowValue:[NSMutableArray arrayWithArray:@[@"深圳市", @"福田区"]] items:items];
    }
    for (NSInteger index = 0; index < [self.showIndexs count]; index ++) {
        
        [self.pickerView selectRow:[[self.showIndexs objectAtIndex:index] integerValue] inComponent:index animated:NO];
    }
    
}

#pragma mark--确定
-(void)doneButtonClickAction:(id)sender{
    
    if (self.selectedItemBlock) {
        NSMutableArray *resultArr = [NSMutableArray array];
        [self.showAddressArr enumerateObjectsUsingBlock:^(NSArray *objArr, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDictionary *selectedItem = [objArr objectAtIndex:[[self.showIndexs objectAtIndex:idx] integerValue]];
            [resultArr addObject:selectedItem];
        }];
        self.selectedItemBlock(resultArr);
    }
    [self dismissWithAnimation:YES];
}



#pragma mark--取消
- (void)cancelButtonClickAction:(id)sender {
    [self dismissWithAnimation:YES];
}


- (void)showWithAnimation:(BOOL)animation{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self];
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundView.alpha = 1;
        CGRect frame = self.pickerContainerView.frame;
        frame.origin.y = SCREEN_HEIGHT - PickerHeight - PickerToolBarHeight;
        self.pickerContainerView.frame = frame;
        
    }];
    
}
- (void)dismissWithAnimation:(BOOL)animation{
    
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
        CGRect frame = self.pickerContainerView.frame;
        frame.origin.y = SCREEN_HEIGHT;
        self.pickerContainerView.frame = frame;
        
    }  completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)setPickerContainerView:(UIView *)pickerContainerView {
    _pickerContainerView = pickerContainerView;
    [self addSubview:_pickerContainerView];
    _pickerContainerView.center = CGPointMake(_alertWindow.center.x, _alertWindow.center.y);
}



- (void)tap:(UITapGestureRecognizer *)tap{
    
    [self  dismissWithAnimation:NO];
}


@end
